-- 定义参数
local voucherId = ARGV[1]
local userId = ARGV[2]
-- 全局唯一ID(订单ID)
local id = ARGV[3]
-- 获取库存
local stockKey = "Seckill:Stock:" .. voucherId
local stock = redis.call("GET", stockKey)

-- 判断库存是否充足
if tonumber(stock) <= 0 then
    return 1
end

-- 判断用户是否已下单
local orderUserKey = "Seckill:OrderUserId:" .. voucherId
local addedCount = redis.call("SADD", orderUserKey, userId)

-- 如果用户已下单
if addedCount == 0 then
    return 2
end

-- 获得下单资格(redis预下单成功)
-- 预扣减库存
redis.call("INCRBY", stockKey, -1)
-- 将订单信息存入消息队列中
-- 添加消息到Stream
local fields = {
    "voucherId", ARGV[1],
    "userId", ARGV[2],
    "id", ARGV[3]
}
redis.call("XADD", "stream.orders", "*", unpack(fields))
return 0
